package common.correspondence;

import com.google.protobuf.InvalidProtocolBufferException;
import common.CIBIO;
import common.NodePointer;
import common.proto.out.CountMessage.CountResult;
import common.proto.out.CountMessage.Cib;
import common.proto.out.CountMessage.Announcement;

import java.util.Arrays;

public class CountWrap {
    public static Message countResultToMessage(CIBIO cibOut, NodePointer to, int from, String id){
        CountResult.Builder resBuild = CountResult.newBuilder();
        resBuild.setRequirementIndex(to.reqIndex);
        resBuild.setSourceNodeIndex(from);
        resBuild.setDestinationNodeIndex(to.index);
        resBuild.setId(id);

        Cib.Builder cibBuild = Cib.newBuilder();
        cibBuild.addAllWithdraw(cibOut.withdraw);

        for(int i=0;i<cibOut.announcements.size();i++){
            common.Announcement a = cibOut.announcements.get(i);
            Announcement.Builder aBuild = Announcement.newBuilder();
            aBuild.setId(a.id);
            aBuild.addAllCount(a.count);
            aBuild.setPredicate(a.predicate);
            Announcement an = aBuild.build();
            cibBuild.setAnnouncements(i, an);
        }
        Cib cib = cibBuild.build();
        resBuild.setCib(cib);
        CountResult cr = resBuild.build();
        return new Message(Message.MessageType.Count.ordinal(), cr.toByteArray());
    }

    public static CountResult messageToCountResult(byte[] message){
        CountResult cr = null;
        try {
            cr = CountResult.parseFrom(message);
//            if(cr.getCib().getAnnouncementsList().size() == 0){
//                System.err.printf("%s, %s\n",Arrays.toString(message), message.length);
//            }
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        return cr;
    }
}
